        package com.boot.springboot.service;

        import com.boot.springboot.pojo.User;
        import com.boot.springboot.pojo.dto.UserDto;
        import com.boot.springboot.repository.UserRepository;
        import org.springframework.beans.BeanUtils;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;
        import org.springframework.transaction.annotation.Transactional;

        import java.util.List;

        @Service  //spring的bean
        public class UserService implements IUserService {

            @Autowired
            UserRepository userRepository;

            @Override
            public User add(UserDto user) {
                User userPojo = new User(); //创一个新的
                BeanUtils.copyProperties(user, userPojo); //把A拷到b里去，类似于复制
                // 修正：通过注入的实例调用save方法
                if (userRepository.findByUserId(userPojo.getUserId()).isPresent()) {
                    throw new IllegalArgumentException("用户ID已存在：" + userPojo.getUserId());
                }
                return userRepository.save(userPojo);
            }

            @Override
            public User get(Integer userId) {
                return userRepository.findByUserId(userId).orElseThrow(() -> {
                    throw new IllegalArgumentException("不存在该用户，异常参数");
                });
            }

            @Override
            public User edit(UserDto user) {
                User userPojo = userRepository.findByUserId(user.getUserId())
                        .orElseThrow(() -> new IllegalArgumentException("用户不存在：" + user.getUserId()));
                BeanUtils.copyProperties(user, userPojo);
                return userRepository.save(userPojo);
            }

            @Transactional//JPA允许get方法通过非主键来进行查询，但detele不允许，所以为delete 方法开启一个数据库事务
            @Override
            public void delete(Integer userId) {
                User user=userRepository.findByUserId(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在，userId：" + userId));
               userRepository.deleteByUserId(userId);

            }
            @Override
            public List<User> getAllUsers() {
                return (List<User>) userRepository.findAll();
            }


        }

